const path = require('path');
//设置根目录
global.rootPath = path.resolve(__dirname);
const config = require(`./config/${process.env.CONFIG}`);
const Koa = require('koa');
const KoaBody = require('koa-body');
const { getClientIP, getUUID } = require('./common.js');
const router = require('./router.js');
const logger = require('./util/logInit.js').createLogger("server");
const { __init } = require('./main.js');

__init(); //启动时执行
const app = new Koa();
app.use(KoaBody({ multipart: true }));

// Koa 应用级中间件
app.use(async (ctx, next) => {
  let uuid = await getUUID();
  ctx.request.uuid = uuid;
  logger.log("info",`[${uuid}]请求方式：${ctx.request.method}`);
  logger.log("info",`[${uuid}]请求URL：${ctx.request.url}`);
  logger.log("info",`[${uuid}]请求IP：${await getClientIP(ctx)}`);
  logger.log("info",`[${uuid}]请求参数：${JSON.stringify(ctx.request.body)}`);
  await next();
  logger.log('info',`[${uuid}]返回状态：${ctx.response.status}`)
  logger.log('info',`[${uuid}]返回结果：${JSON.stringify(ctx.response.body)}`)
});

const errorHandler = async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    console.log(err);
    ctx.response.status = err.statusCode || err.status || 500;
    ctx.response.body = {
      message: err.message
    };
  }
};

app
  .use(errorHandler)
  .use(router.routes())
  .use(router.allowedMethods());

app.on('error', function (err) {
  console.log(err);
});

app.listen(config.port,()=>{
  console.log(`server start at port : ${config.port}`);
});
